package org.wuqinghua.chapter01;

import org.drools.core.marshalling.impl.ProtobufMessages;
import org.junit.Test;
import org.kie.api.io.ResourceType;
import org.kie.internal.KnowledgeBase;
import org.kie.internal.builder.KnowledgeBuilder;
import org.kie.internal.builder.KnowledgeBuilderFactory;
import org.kie.internal.definition.KnowledgePackage;
import org.kie.internal.io.ResourceFactory;
import org.kie.internal.runtime.StatefulKnowledgeSession;
import org.wuqinghua.model.Goods;

import java.util.Collection;

/**
 * Created by wuqinghua on 18/4/8.
 * <p>
 * 场景:某类商品(Goods)现在需要进行折扣处理.根据市场行情可不断的变更
 *    - 变更的时候只需要修改规则文件即可
 */
public class Drools5APITest {

    @Test
    public void drools5ApiTest() {
        // 1. 创建Builder
        KnowledgeBuilder knowledgeBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
        // 2. 添加规则文件路径
        knowledgeBuilder.add(ResourceFactory.newClassPathResource("com/rules/goods.drl", this
                .getClass()), ResourceType.DRL);

        if (knowledgeBuilder.hasErrors()) {
            System.out.println(knowledgeBuilder.getErrors());
        }

        // 3.构建Base
        KnowledgeBase knowledgeBase = knowledgeBuilder.newKnowledgeBase();
        Collection<KnowledgePackage> knowledgePackages = knowledgeBase.getKnowledgePackages();
        knowledgeBase.addKnowledgePackages(knowledgePackages);

        // 4.构建Session
        StatefulKnowledgeSession statefulKnowledgeSession = knowledgeBase.newStatefulKnowledgeSession();


        Goods goods = new Goods();
        System.out.println("old discount is :" + goods.getDiscount() + "%");


        statefulKnowledgeSession.insert(goods);
        // 执行引擎,返回的匹配的规则数量
        int count = statefulKnowledgeSession.fireAllRules();
        statefulKnowledgeSession.dispose();

        System.out.println("Fire " + count + " rule(s).");
        System.out.println("new discount is :" + goods.getDiscount() + "%");


    }
}
